package org.springblade.modules.alimqtt.service;

import com.alibaba.fastjson.JSON;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.onsmqtt20200420.AsyncClient;
import com.aliyun.sdk.service.onsmqtt20200420.models.RegisterDeviceCredentialRequest;
import com.aliyun.sdk.service.onsmqtt20200420.models.RegisterDeviceCredentialResponse;
import com.aliyun.sdk.service.onsmqtt20200420.models.RegisterDeviceCredentialResponseBody;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.alimqtt.config.AliyunMqttProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class DeviceCredentialService {
	@Resource
	private AliyunMqttProperties aliyunMqttProperties;

	public RegisterDeviceCredentialResponseBody.DeviceCredential registerDevice(String deviceCode) {
		StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
			.accessKeyId(aliyunMqttProperties.getAccessKey())
			.accessKeySecret(aliyunMqttProperties.getSecretKey())
			.build());

		AsyncClient client = AsyncClient.builder()
			.credentialsProvider(provider)
			.overrideConfiguration(
				ClientOverrideConfiguration.create()
					.setEndpointOverride(aliyunMqttProperties.getEndpoint())
					.setConnectTimeout(Duration.ofSeconds(30))
			)
			.build();
		RegisterDeviceCredentialRequest build = RegisterDeviceCredentialRequest.builder()
			.clientId(aliyunMqttProperties.getDoorGroupId() + "@@@" + deviceCode)
			.instanceId(aliyunMqttProperties.getInstance()).build();
		CompletableFuture<RegisterDeviceCredentialResponse> response = client.registerDeviceCredential(build);
		RegisterDeviceCredentialResponseBody.DeviceCredential deviceCredential = null;
		try {
			deviceCredential = response.get().getBody().getDeviceCredential();
		} catch (Exception e) {
			log.error("阿里云mqtt注册失败", e);
		}
		log.info("设备注册{}===>{}",deviceCode, JSON.toJSONString(deviceCredential));
		return deviceCredential;

	}

}
